#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qjson/parser.h>
#include <QFile>
#include <QDebug>
#include <QIcon>
#include <QToolBar>
#include "pluginloader.h"
#include <QSettings>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_sqlQuery = new SqlQuery;
    m_luaExecuter = new LuaExecuter;

    QMdiSubWindow *sqlQuery = new QMdiSubWindow;
    sqlQuery->setWidget(m_sqlQuery);
    sqlQuery->setAttribute(Qt::WA_DeleteOnClose, false);
    ui->mdiArea->addSubWindow(sqlQuery);
    sqlQuery->hide();

    QMdiSubWindow *luaExecuter = new QMdiSubWindow;
    luaExecuter->setWidget(m_luaExecuter);
    luaExecuter->setAttribute(Qt::WA_DeleteOnClose, false);
    ui->mdiArea->addSubWindow(luaExecuter);
    luaExecuter->hide();

    initQSMenu("queries.json", "queries", ui->menuQueries, SLOT(execQuery()));
    initQSMenu("scripts.json", "scripts", ui->menuScripts, SLOT(execScript()));

    buildPeopleTree();
    m_profile = new Profile;
    m_profileMdi = new QMdiSubWindow;
    m_profileMdi->setWidget(m_profile);
    m_profileMdi->setAttribute(Qt::WA_DeleteOnClose, false);
    ui->mdiArea->addSubWindow(m_profileMdi);
    m_profileMdi->hide();
    connect(ui->treeView, SIGNAL(doubleClicked(QModelIndex)),
            this, SLOT(loadProfile(QModelIndex)));

    QToolBar *toolBar = addToolBar(tr("Plugins"));
    toolBar->setObjectName("plugins_toolbar");
    PluginLoader loader(this, ui->mdiArea, ui->menuPlugins, toolBar);
    loader.load();

    QSettings settings("romix.lab", "acs");
    restoreGeometry(settings.value("main_window_gm").toByteArray());
    restoreState(settings.value("main_window_st").toByteArray());
    m_profileMdi->restoreGeometry(settings.value("profile_mdi_gm").toByteArray());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::execQuery()
{
    QAction *act = (QAction *)sender();
    QString file = act->property("file").toString();
    m_sqlQuery->loadQuery(file);
    m_sqlQuery->show();
}

void MainWindow::execScript()
{
    QAction *act = (QAction *)sender();
    QString file = act->property("file").toString();
    m_luaExecuter->execScript(file);
    m_luaExecuter->show();
}

void MainWindow::loadProfile(const QModelIndex &index)
{
    PeopleTreeNode *node = (PeopleTreeNode *)index.internalPointer();
    if (node) {
        if (node->type() != "group") {
            m_profile->loadProfile(node->id());
            m_profile->setWindowTitle(tr("Profile: %1").arg(node->name()));
           // m_profile->resize(m_profile->minimumSize());
            //m_profileMdi->resize(m_profile->minimumSize());
            m_profileMdi->resize(m_profileMdi->sizeHint());
            m_profile->show();
        }
    }
}

void MainWindow::closeEvent(QCloseEvent *e)
{
    QSettings settings("romix.lab", "acs");
    settings.setValue("main_window_gm", saveGeometry());
    settings.setValue("main_window_st", saveState());
    settings.setValue("profile_mdi_gm", m_profileMdi->saveGeometry());

    QMainWindow::closeEvent(e);
}

void MainWindow::initQSMenu(const QString &filename, const QString &jsonNode, QMenu *parentMenu, const char *member)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << QString("Can't open %1 list, file didn't exist!").arg(filename);
        return;
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");
    QString json = in.readAll();
    file.close();

    bool ok;
    QJson::Parser parser;
    QVariantList queries = parser.parse(json.toUtf8(), &ok).toMap()[jsonNode].toList();

    QHash<QString, QMenu*> m_queries_menu;
    for (int i = 0; i < queries.count(); ++i) {
        QVariantMap query = queries[i].toMap();
        QString menu = query["menu"].toString();

        QMenu *m;
        if (m_queries_menu.contains(menu)) {
            m = m_queries_menu[menu];
        } else {
            m = parentMenu->addMenu(menu);
            m_queries_menu.insert(menu, m);
        }
        QAction *act = m->addAction(query["name"].toString(), this, member);
        act->setProperty("file", query["file"].toString());
    }
}

void MainWindow::buildPeopleTree()
{
    ui->treeView->setIconSize(QSize(24, 24));
    m_peopleTreeModel = new PeopleTreeModel(this);
    ui->treeView->setModel(m_peopleTreeModel);
}
